package com.example.demo.controller;


import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;


//@Component
public class ZookeeperWatcher {
	
	private static String zNode ="/mysql";
	public static void watcherZnode() throws Exception {
		System.out.println("start to subscribeDataChanges");
		// 获取zkClient对象
        final ZkClient zkClient = new ZkClient("linux168:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        //判断节点是否存在，不存在创建节点并赋值
        final boolean exists = zkClient.exists(zNode);
        if (!exists) {
        	System.out.println("create znode");
            zkClient.createPersistent(zNode, "mytest");
        }
        //注册监听器，节点数据改变的类型，接收通知后的处理逻辑定义
        zkClient.subscribeDataChanges(zNode, new IZkDataListener() {
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println(path + " data is changed ,new data " + data);
                DBUtil.closeConnection();
                DBUtil.dbname = data.toString();
            }

            //数据删除--》节点删除
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path + " is deleted!!");
            }
        });
        

	}

}
